package br.com.triad.testelucasdsniel;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class WebServiceEventos {

	public WebServiceEventos() {
	}
	
	private String toString(InputStream is) throws IOException {
		byte[] bytes = new byte[1024];
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int lidos;
		while ((lidos = is.read(bytes)) > 0) {
			baos.write(bytes, 0, lidos);
		}
		return new String(baos.toByteArray());
	}

	private String getRESTFileContent(String url) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(url);
		try {
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream instream = entity.getContent();
				String result = toString(instream);
				instream.close();
				return result;
			}
		} catch (Exception e) {
			Log.e("WEBSERVICE", "Falha ao acessar Web service", e);
		}
		return null;
	}
	
	public void atualizarEventos() {
		String result = getRESTFileContent("http://www.meuwebservice.com.br:7071/listar_eventos");
		//TODO aqui atualizar o banco e persistir os dados recebidos, sendo aqui um PARSER JSON ou XML...
	}
}
